/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ts, native, HomeCheckHint } from 'qvog-dsl';

const SEVERITY = 2;
const DOC_PATH = 'docs/no-confusing-non-null-assertion.md';
const DESCRIPTION = 'Confusing combinations of non-null assertion and equal test like "a! == b", which looks very similar to not equal "a !== b".';

export default native<HomeCheckHint>()()
  .match(ts.isBinaryExpression)
  .when((node: ts.BinaryExpression): boolean => {
    const operator = node.operatorToken.getText();
    if (!['=', '==', '==='].includes(operator)) { return false };

    const leftHandFinalToken = node.left.getLastToken();
    const tokenAfterLeft = getNextToken(leftHandFinalToken, node.getSourceFile());

    if (!hasConfusingExclamation(leftHandFinalToken, tokenAfterLeft)) { return false };

    return containsNonNullAssertion(node.left);
  })
  .report({
    severity: SEVERITY,
    description: DESCRIPTION,
    docPath: DOC_PATH
  });


function hasConfusingExclamation(leftHandFinalToken?: ts.Node, tokenAfterLeft?: ts.Node): boolean {
  return leftHandFinalToken?.kind === ts.SyntaxKind.ExclamationToken &&
    tokenAfterLeft?.kind !== ts.SyntaxKind.CloseParenToken;
}

function containsNonNullAssertion(node: ts.Node): boolean {
  if (ts.isNonNullExpression(node)) { return true };
  return node.getChildren().some(child => containsNonNullAssertion(child));
}

function getNextToken(token: ts.Node | undefined, sourceFile: ts.SourceFile): ts.Node | undefined {
  if (!token) { return undefined };
  const scanner = ts.createScanner(ts.ScriptTarget.Latest, false, ts.LanguageVariant.Standard, sourceFile.getFullText());
  scanner.setTextPos(token.end);
  while (true) {
    const tokenSyntaxKind = scanner.scan();
    if (tokenSyntaxKind === ts.SyntaxKind.EndOfFileToken) { break };

    const nextTokenStart = scanner.getTokenPos();
    const nextTokenEnd = scanner.getTextPos();
    const nextTokenText = sourceFile.text.substring(nextTokenStart, nextTokenEnd);

    if (!/\s/.test(nextTokenText) && !isComment(nextTokenText)) {
      return findNodeAtPosition(sourceFile, nextTokenStart, nextTokenEnd);
    }
  }
  return undefined;
}

function findNodeAtPosition(sourceFile: ts.SourceFile, start: number, end: number): ts.Node | undefined {
  let result: ts.Node | undefined = undefined;
  ts.forEachChild(sourceFile, node => {
    if (node.pos <= start && node.end >= end) {
      result = node;
    }
  });
  return result;
}

function isComment(text: string): boolean {
  return /\/\*[\s\S]*?\*\/|\/\/.*/.test(text);
}
